/**
 * @Project Name:sso.demo1
 * @Package Name:io.hexin.servlet
 * @Since JDK 1.8
 */
package io.hexin.servlet;

import com.alibaba.fastjson.JSONObject;
import io.hexin.bean.User;
import io.hexin.config.Constant;
import io.hexin.service.common.JwtService;
import io.hexin.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 刷新Token控制器
 * @Author 胡松 hoofungson@163.com
 * @Date 2017-11-07 15:15
 * @Version V1.0
 */
@Controller
@RequestMapping("/token")
public class RefreshTokenController {

    private Logger logger = LogManager.getLogger(RefreshTokenController.class);


    @Autowired
    private JwtService jwtService;

    @ResponseBody
    @RequestMapping(value = "/refreshToken")
    public String refreshToken(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/event-stream;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        response.setCharacterEncoding("UTF-8");
        String token = request.getParameter("token");
        if(jwtService.validateJWT(token)){
            Claims claims = jwtService.parseJWT(token);
            String json = claims.getSubject();
            User user = JSONObject.parseObject(json, User.class);
            String subject = JwtUtil.generalSubject(user);
            String refreshToken = jwtService.createJWT(Constant.JWT_ID, subject, Constant.JWT_TTL);
            String result = "retry:" + Constant.JWT_REFRESH_INTERVAL + "\n";
            result += "data: " + refreshToken + "\n\n";
            return result;
        }
        return "token无效或过期！";
    }
}
